package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2VO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redisson;

    CategoryBrandRelationService categoryBrandRelationService;
/*
    @Caching(evict = {
            @CacheEvict(value = "category", key = "'getLeval1Category'"),
            @CacheEvict(value = "category", key = "'getCatalogJSON'")
    })*/
    @CacheEvict(value = "category", allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        //在CategoryBrandRelationServiceImpl中创建updateCategory这个方法
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //2.组装成父子的树状分类
        List<CategoryEntity> level = categoryEntities.stream()
                .filter(categoryEntity ->
                        categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, categoryEntities));
                    return categoryEntity;
                }).sorted((m1, m2) -> m1.getSort() - m2.getSort()).collect(Collectors.toList());

        return level;
    }

    @Override
    public List<CategoryEntity> getLeval1Category() {


        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public Map<String, List<Catalog2VO>> getCatalogJson() {

        /**
         * 1.将数据库的多次查询变成一次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有1级分类
        List<CategoryEntity> leval1Category = getParent_cid(selectList, 0L);

        //封装数据
        Map<String, List<Catalog2VO>> map = leval1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个一级分类，查找这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catalog2VO> catalog2VOS = null;
            if (categoryEntities != null) {
                catalog2VOS = categoryEntities.stream().map(l2 -> {
                    Catalog2VO catalog2VO = new Catalog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找到当前二级分类的三级分类
                    List<CategoryEntity> level3Catalog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catalog != null) {
                        List<Catalog2VO.Catalog3VO> collect = level3Catalog.stream().map(l3 -> {
                            //封装成指定格式
                            Catalog2VO.Catalog3VO catalog3VO = new Catalog2VO.Catalog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return catalog3VO;
                        }).collect(Collectors.toList());
                        catalog2VO.setCatalog3List(collect);
                    }
                    return catalog2VO;
                }).collect(Collectors.toList());
            }
            return catalog2VOS;
        }));

        return map;
    }

    @Override
    public Long[] findCatalogPath(Long catalogId) {
        List<Long> paths = new ArrayList<>();
        findParentPath(catalogId, paths);
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }
    private List<Long> findParentPath(Long catalogId, List<Long> paths) {
        paths.add(catalogId);
        CategoryEntity entity = this.getById(catalogId);
        if (entity.getParentCid() != 0) {
            findParentPath(entity.getParentCid(), paths);
        }
        return paths;
    }

    //    @Override
    public Map<String, List<Catalog2VO>> getCatalogJson2() {
        //假如缓存中的数据是JSON字符串
        //json字符串具有跨平台语言兼容性

        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //缓存中没有，就需要查询数据库
            Map<String, List<Catalog2VO>> catalogJsonFromDB = getCatalogJsonFromDBWithRedisLock();


            return catalogJsonFromDB;
        }

        //返回时需要将json反序列化为需要的map对应类型返回
        //进行json反序列化
        Map<String, List<Catalog2VO>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2VO>>>() {
        });
        return result;

    }

    //从数据库查询并封装，通过redis分布式锁实现
    public Map<String, List<Catalog2VO>> getCatalogJsonFromDBWithRedissonLock() {

        //1.锁的名字，锁的粒度，越细越快
        //锁的粒度：具体缓存的是某个数据，product-11-lock product-12-lock,分别给11，12加；如果直接给product加锁，那么11，12都会锁住；
        RLock lock = redisson.getLock("catalogJSON-lock");
        lock.lock();

        Map<String, List<Catalog2VO>> dataFromDB;
        try {
            dataFromDB = getDataFromDB();
        } finally {
            lock.unlock();
        }
        return dataFromDB;

    }


    //从数据库查询并封装，通过redis分布式锁实现
    public Map<String, List<Catalog2VO>> getCatalogJsonFromDBWithRedisLock() {

        String uuid = UUID.randomUUID().toString();
        //1.占分布式锁
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功
            //需要设置过期时间
            /*stringRedisTemplate.expire("lock", 30, TimeUnit.SECONDS);
            Map<String, List<Catalog2VO>> dataFromDB = getDataFromDB();
            if (uuid.equals(stringRedisTemplate.opsForValue().get("lock"))) {
                stringRedisTemplate.delete("lock");//删除锁
            }*/
            Map<String, List<Catalog2VO>> dataFromDB;
            try {
                dataFromDB = getDataFromDB();
            } finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                Integer lock1 = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Integer.class)
                        , Arrays.asList("lock"), uuid);

            }
            return dataFromDB;

        } else {
            //加锁失败。。重试
            //避免重试次数太多，可以休眠适当时间
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                log.error("redis缓存处理:{}", e);
            }
            return getCatalogJsonFromDBWithRedisLock();
        }

    }

    private Map<String, List<Catalog2VO>> getDataFromDB() {
        //得到锁之后再做一次判断，如果有了就直接释放
        String s = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(s)) {
            Map<String, List<Catalog2VO>> result = JSON.parseObject(s, new TypeReference<Map<String, List<Catalog2VO>>>() {
            });
            return result;
        }

        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有1级分类
        List<CategoryEntity> leval1Category = getParent_cid(selectList, 0L);

        //封装数据
        Map<String, List<Catalog2VO>> map = leval1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个一级分类，查找这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catalog2VO> catalog2VOS = null;
            if (categoryEntities != null) {
                catalog2VOS = categoryEntities.stream().map(l2 -> {
                    Catalog2VO catalog2VO = new Catalog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找到当前二级分类的三级分类
                    List<CategoryEntity> level3Catalog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catalog != null) {
                        List<Catalog2VO.Catalog3VO> collect = level3Catalog.stream().map(l3 -> {
                            //封装成指定格式
                            Catalog2VO.Catalog3VO catalog3VO = new Catalog2VO.Catalog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return catalog3VO;
                        }).collect(Collectors.toList());
                        catalog2VO.setCatalog3List(collect);
                    }
                    return catalog2VO;
                }).collect(Collectors.toList());
            }
            return catalog2VOS;
        }));
        //将查到的数据放入缓存,但是不能直接放，需要转换为json型的字符串
        String result = JSON.toJSONString(map);
        stringRedisTemplate.opsForValue().set("catalogJSONN", result, 1, TimeUnit.DAYS);

        return map;
    }


    //从数据库查询并封装，通过本地锁实现
    public Map<String, List<Catalog2VO>> getCatalogJsonFromDBWithLocalLock() {

        //使用本地锁
        synchronized (this) {
            //得到锁之后再做一次判断，如果有了就直接释放
            String s = stringRedisTemplate.opsForValue().get("catalogJSON");
            if (!StringUtils.isEmpty(s)) {
                Map<String, List<Catalog2VO>> result = JSON.parseObject(s, new TypeReference<Map<String, List<Catalog2VO>>>() {
                });
                return result;
            }

        }

        /**
         * 1.将数据库的多次查询变成一次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有1级分类
        List<CategoryEntity> leval1Category = getParent_cid(selectList, 0L);

        //封装数据
        Map<String, List<Catalog2VO>> map = leval1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个一级分类，查找这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catalog2VO> catalog2VOS = null;
            if (categoryEntities != null) {
                catalog2VOS = categoryEntities.stream().map(l2 -> {
                    Catalog2VO catalog2VO = new Catalog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找到当前二级分类的三级分类
                    List<CategoryEntity> level3Catalog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catalog != null) {
                        List<Catalog2VO.Catalog3VO> collect = level3Catalog.stream().map(l3 -> {
                            //封装成指定格式
                            Catalog2VO.Catalog3VO catalog3VO = new Catalog2VO.Catalog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return catalog3VO;
                        }).collect(Collectors.toList());
                        catalog2VO.setCatalog3List(collect);
                    }
                    return catalog2VO;
                }).collect(Collectors.toList());
            }
            return catalog2VOS;
        }));
        //将查到的数据放入缓存,但是不能直接放，需要转换为json型的字符串
        String s = JSON.toJSONString(map);
        stringRedisTemplate.opsForValue().set("catalogJSONN", s, 1, TimeUnit.DAYS);

        return map;
    }


    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        return selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
    }


    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                }).sorted((m1, m2) -> (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort())).collect(Collectors.toList());
        return children;
    }
}
